function getQueryParameter(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

document.addEventListener('DOMContentLoaded', (event) => {
    const categoryId = getQueryParameter('categoryId');
    const categoryMap = {
        '1': { name: '前端', image: '../pic/前端.webp' },
        '2': { name: '后端', image: '../pic/后端.webp' },
        '3': { name: '数据库', image: '../pic/数据库.webp' }
    };

    const category = categoryMap[categoryId];

    if (category) {
        document.getElementById('category-name').innerText = category.name;
        document.getElementById('category-image').src = category.image;
        document.getElementById('category-image').alt = `${category.name} 图片`;
    } else {
        document.getElementById('category-name').innerText = '未知分类';
        document.getElementById('category-image').src = '../pic/default.webp'; // 如果没有找到匹配的分类图片，可以使用默认图片
        document.getElementById('category-image').alt = '默认图片';
    }

    // 获取文章列表并显示在页面上
    fetch(`http://localhost:8888/articles/category/${categoryId}`)
    .then(response => response.json())
    .then(data => {
        console.log(data);  // 添加此行来调试
        const articleList = document.querySelector('.article-list');
        articleList.innerHTML = ''; // 清空当前文章列表

        if (data.code === 200) {
            data.data.forEach(article => {
                const articleElement = document.createElement('div');
                articleElement.className = 'article';
                articleElement.innerHTML = `
                    <h2>${article.title}</h2>
                    <p>${article.summary}</p>
                    <div class="article-footer">
                        <span>作者: ${article.account}</span>
                        <span>发布时间: ${new Date(article.createDate).toLocaleDateString()}</span>
                    </div>
                `;
                articleElement.addEventListener('click', () => {
                    window.location.href = `blog_detail.html?articleId=${article.id}`;
                });
                articleList.appendChild(articleElement);
            });
        } else {
            articleList.innerHTML = '<p>无法获取文章列表</p>';
        }
    })
    .catch(error => {
        console.error('Error fetching articles:', error);
        document.querySelector('.article-list').innerHTML = '<p>无法获取文章列表</p>';
    });
});

function redirectTo(page) {
    window.location.href = page;
}
